<?php

namespace app\admin\service;

use app\admin\model\Abnormal;
use app\admin\model\City;
use app\admin\model\Disease;
use app\admin\model\Illegal;
use app\admin\model\Unit;
use app\admin\model\User;
use think\Request;


/**
 * 道路交通-病害管理
 */
class IllegalService extends BaseService
{
    public function __construct()
    {
        $this->name = 'WJ';
        $this->model_type = 'illegal';
        $this->model = new Illegal();
    }

    public function lists(array $param)
    {
        $query = $this->model->where('mark', 1)
            ->with(
                [
                    'unit' => function ($query) {
                        $query->field('id, unit_name');
                    },
                    'abnormal' => function ($query) {
                        $query->field('id, name');
                    },
                    'user' => function ($query) {
                        $query->field('id, realname');
                    }
                ]
            );
        if (!empty($param['operation_no'])) {
            $query->whereLike('operation_no', '%' . $param['operation_no'] . '%');
        }
        if (!empty($param['organization_id'])) {
            $query->where('organization_id', $param['organization_id']);
        }
        if (!empty($param['operation_category'])) {
            $query->where('operation_category', $param['operation_category']);
        }
        if (!empty($param['exception_category'])) {
            $query->where('exception_category', $param['exception_category']);
        }
        if (!empty($param['area_id'])) {
            $query->where('area_id', end($param['area_id']));
        }
        if (isset($param['organization_show'])) {
            $query->where('organization_show', $param['organization_show']);
        }
        if (isset($param['penalty'])) {
            $query->where('penalty', $param['penalty']);
        }
        if (isset($param['create_user'])) {
            $userid = User::whereLike('realname', "%" . $param['create_user'] . "%")->column('id');
            if (empty($userid)) {
                $userid = [0];
            }
            $query->whereIn('create_user', implode(',', $userid));
        }
        $data = [
            'msg' => '操作成功',
            'code' => 0,
            'data' => [],
            'count' => (clone $query)->count('id'),
        ];
        if ($data['count']) {
            $data['data'] = $query->order('id', 'desc')
                ->page(PAGE, PERPAGE)
                ->select();

            $areaIds = [];
            foreach ($data['data'] as $val) {
                $areaIds[] = substr($val['area_id'], 0, 2) . '0000';
                $areaIds[] = substr($val['area_id'], 0, 4) . '00';
                $areaIds[] = $val['area_id'];
            }
            $areas = City::whereIn('citycode', $areaIds)->column('name', 'citycode');
            $unitModel = new Unit();
            $abmodel = new Abnormal();
            $adminModel = new User();
            foreach ($data['data'] as &$val) {
                $val['area'] = $areas[substr($val['area_id'], 0, 2) . '0000'] ?? '';
                $val['area'] .= $areas[substr($val['area_id'], 0, 4) . '00'] ?? '';
                $val['area'] .= $areas[$val['area_id']] ?? '';
                $val['area'] .= $val['address'];
                $unit = $unitModel->where(['id' => $val['organization_id']])->find();
                $val['unit_name'] = $unit['unit_name'];
                $pval = $abmodel->getInfo($val['exception_category']);
                $val['exception_name'] = empty($pval) ? '' : $pval['name'];
                $val['username'] = $adminModel->where(['id' => $val['create_user']])->value('realname');
                $val['shenhe'] = $adminModel->whereIn('id', $val['shen_ids'])->field('id,realname')->select();
            }
        }

        return $data;
    }

    public function info()
    {
        $id = request()->param('id', 0);
        $info = $this->model->getInfo($id);
        $info['images'] = $info['images'] ? json_decode($info['images'], true) : [];
        $info['area_id'] = [
            (substr($info['area_id'], 0, 2) . '0000'),
            (substr($info['area_id'], 0, 4) . '00'),
            (string)$info['area_id']
        ];

        $info['diff_points'] = $info['diff_points'] ? json_decode($info['diff_points'], true) : [];

        return message("操作成功", true, $info);
    }

    public function edit()
    {
        $data = request()->param();
        $data['area_id'] = end($data['area_id']);
        $data['images'] = json_encode($data['images']);
        $data['diff_points'] = isset($data['diff_points'])?json_encode($data['diff_points']):json_encode([]);

        return parent::edit($data);
    }

    public function setShow($id)
    {
        if (is_array($id)) {
            $query = Disease::where('id', 'in', $id);
        } else {
            $query = Disease::where('id', $id);
        }
        $query->update(['organization_show' => 1]);

        return message();
    }

    public function compareImg()
    {
        $images = request()->param('images');

        if(is_array($images)){
            $filepath = $images[0];
            $filepath2 = $images[1];
        }

        $filepath = str_replace(IMG_URL, 'uploads',$filepath);
        $filepath2 = str_replace(IMG_URL, 'uploads',$filepath2);

        // 判断两张图片的宽高是否一致
        $before_img_info = getimagesize($filepath);
        $before_img_w = $before_img_info[0];
        $before_img_h = $before_img_info[1];

        $img_info = getimagesize($filepath2);
        $img_w = $img_info[0];
        $img_h = $img_info[1];


        if ($before_img_w != $img_w || $before_img_h != $img_h) {
            return message("两张图片的宽高不一致,无法比对图片", false);
        }

        // 远程API接口路径
        // $uploadurl = "http://1e46dad4.r8.cpolar.top/uploadfiles";
        $uploadurl = "http://127.0.0.1:8000/uploadfiles";

        // 要提交的表单数据
        $post_data = array(
            'befrore_image' => new \CURLFile(realpath($filepath), $before_img_info['mime'], md5(time()).'.png'),
            'image' => new \CURLFile(realpath($filepath2), $before_img_info['mime'], md5(time()+1).'.png'),
        );

        $headers = [
            'Content-Type:multipart/form-data',
        ];

        $res = $this->postCurl($uploadurl, $post_data, $headers);
        $arr = json_decode($res, true);

        $dir = 'uploads/out';
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }

        $image = new \Water;
        $save_file = 'nopic.png';
        if (isset($arr['message']) && $arr['message'] == 'success') {
            $points = $arr['list'];
            $save_file = 'uploads/out/' . time() . '.png';
            $image->watermark(realpath($filepath2), $points, $save_file, PUBLIC_PATH . '/static/mark.png');
        } else {
            return message("图片对此错误:" . $arr['message'], false);
        }

        $info['url'] = IMG_URL . str_replace('uploads','',$save_file);
        foreach ($points as &$point){
            $point['showModal'] = false;
        }
        unset($point);
        $info['points'] = $points;

        return message("操作成功", true, $info);
    }

    public function submitMark($filepath,$pointsArr){

        $dir = 'uploads/out';
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }

        // $filepath = "uploads/temp/20230915/d45c858b7e04b47bb74e16334ce3e486.png";
        $filepath2 = str_replace(IMG_URL, 'uploads',$filepath);
        $image = new \Water();
        $save_file = 'uploads/out/' . time() . '.png';
        $image->watermark(realpath($filepath2), $pointsArr, $save_file, PUBLIC_PATH . '/static/mark.png');

        // http://images.wurenji.test/out/1694849015.png
        // D:/www/wurenji_houtai/public/out/1694849015.png
        $info['url'] = IMG_URL .  str_replace('uploads','',$save_file);
        $info['points'] = $pointsArr;

        return message("操作成功", true, $info);
    }

    public function getLastImageByAddress($address)
    {
        $json = \app\admin\model\Operation::where(['address' => $address])->order('id desc')->value('images');

        if ($json) {
            $arr = json_decode($json, true);
            $info = [];
            // 最多三张图
            if (count($arr) >=2) {
                $info['url'] = $arr[1];
            } elseif (count($arr) == 1) {
                $info['url'] = $arr[0];
            }

            return message("该打标点上传过图片", true, $info);
        }

        return message("该打标点未上传过图片", false);

    }

    function postCurl($url, $post_data, $headers)
    {

        // 初始化cURL会话
        $curl = curl_init();
        // 设置cURL选项
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        //设置header头信息
        #curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 300);

        // 关闭SSL验证
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

        // 执行cURL请求
        $response = curl_exec($curl);
        // 关闭cURL会话
        curl_close($curl);
        return $response;
    }
}

